import store from '@/store'
import {
	BASE
} from '@/const/base.js'
import {
	HTTP_STATUS,
	HTTP_STATUS_CODE
} from '@/const/status'
import storage from './storage.js'
import api from '@/service/config/api.js'
import moment from 'moment';
export const logError = (name, action, info) => {
	if (!info) {
		info = 'empty'
	}
	try {
		let deviceInfo = uni.getSystemInfoSync()
		var device = JSON.stringify(deviceInfo)
	} catch (e) {
		console.error('not support getSystemInfoSync api', err.message)
	}
	let time = formatTime(new Date())
	console.error(time, name, action, info, device)
	// 如果使用了 第三方日志自动上报
	// if (typeof action !== 'object') {
	// fundebug.notify(name, action, info)
	// }
	// fundebug.notifyError(info, { name, action, device, time })
	if (typeof info === 'object') {
		info = JSON.stringify(info)
	}
}
//检查登录态
export const checkLogin = (redirect = true) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('access_token')
		if (!token) {
			redirect &&
				uni.navigateTo({
					url: '/pages/login/index',
				})
			return reject()
		}
		resolve()
	})
}
// loading效果
export const loading = (params = {}) => {
	uni.showLoading({
		title: '请稍等',
		mask: true,
		...params,
	})
}
// toast
export const showToast = (msg, duration = 1500, delta, url, icon = 'none') => {
	uni.showToast({
		title: msg,
		duration,
		mask: true,
		icon,
	})
	if (delta) {
		setTimeout(() => {
			navigateBack(delta)
		}, duration)
	} else if (url) {
		uni.reLaunch({
			url,
		})
	}
}
// modal
export const showModal = ({
	titile,
	content,
	confirmText,
	cancelText,
}) => {
	return new Promise((resolve, reject) => {
		store.commit('setShowModalReady', false);
		uni.showModal({
			title: titile || '提示',
			content: content || '',
			confirmColor: '#F08519',
			cancelColor: '#999999',
			confirmText: confirmText || '确定',
			cancelText: cancelText || '我再想想',
			success: res => {
				store.commit('setShowModalReady', true);
				if (res.confirm) {
					resolve()
				}
			},
			fail: () => {
				store.commit('setShowModalReady', true);
				reject()
			}
		})
	})

}
// 返回上一级
export const navigateBack = (delta, url) => {
	if (getCurrentPages().length == 1) {
		return uni.reLaunch({
			url: url ? url : '/pages/index/index',
		})
	}
	uni.navigateBack({
		delta,
	})
}
/* 隐藏手机号 */
export const hideTel = (tel) => {
	if (!tel) return ''
	const reg = /^(\d{3})\d{4}(\d{4})$/;
	return tel.replace(reg, "$1****$2");
}
/* 隐藏昵称 */
export const hideName = (name) => {
	const reg = /^(.{2}).*(.{2})$/;
	return name.replace(reg, "$1**$2");
}
/* 获取静态资源URL */
export const getStaticUrl = (url) => {
	if (!url) {
		return ''
	}
	const reg = /^(http|https)/;
	return reg.test(url) ? url : BASE.BASE_STATIC_URL + url;
}
/* 获取用户类型 */
export const getUserType = (params) => {
	if (params == 2) {
		return 3
	} else {
		if (params.manager) {
			return 2
		} else if (params.guide) {
			return 1
		} else {
			return 4
		}
	}
}
/* 获取订单状态 */
export const getOrderStatus = (status) => {
	switch (status) {
		case 2:
			return '待确认'
		case 5:
			return '待支付'
		case 6:
			return '待确认收款'
		case 7:
			return '备货中'
		case 8:
			return '待支付尾款'
		case 9:
			return '待确认尾款'
		case 10:
			return '待收货'
		case 11:
			return '待安装'
		case 12:
			return '已完成'
		case 13:
			return '已取消'
		default:
			return ''
	}
}
//判定是否为空
export const isEmpty = (str) => {
	if (typeof str == 'object') {
		for (var key in str) {
			return false;
		}
		return true; //返回true，为空对象
	} else {
		if (typeof str == "undefined" || str == '' || str == null) {
			return true;
		} else if (typeof str == "Array" && !str.length) {
			return true;
		} else {
			return false;
		}
	}
}
/**
 * 解决两个数相乘精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */
export const floatMul = (a, b) => {
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
	} catch (f) {}
	try {
		c += e.split(".")[1].length;
	} catch (f) {}
	return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
/**
 * 解决两个数相加精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */
export const floatAdd = (a, b) => {
	var c, d, e;
	if (undefined == a || null == a || "" == a || isNaN(a)) {
		a = 0;
	}
	if (undefined == b || null == b || "" == b || isNaN(b)) {
		b = 0;
	}
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	e = Math.pow(10, Math.max(c, d));
	return (floatMul(a, e) + floatMul(b, e)) / e;
}

// 浮点数相减
export const floatSub = (num1, num2) => {
	function getDecimalLength(num) {
		let str = num.toString();
		return str.indexOf('.') !== -1 ? str.split('.')[1].length : 0;
	}

	function convertToInt(num, factor) {
		return Math.round(num * factor);
	}
	let factor = Math.pow(10, Math.max(getDecimalLength(num1), getDecimalLength(num2)));
	return (convertToInt(num1, factor) - convertToInt(num2, factor)) / factor;
}

// 获取functionRange
export const getFunctionRange = () => {
	if (store.state.appType == BASE.ADMIN_TYPE) {
		return 0
	} else {
		return store.state.appId
	}
}

// 富文本添加样式
export const formatRichText = (html) => {
	if (!html) return ''
	// html 就是你要传进来地富文本参数
	// 去掉img标签里的style、width、height属性
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]*"/gi, '').replace(/style='[^']*'/gi, '');
		match = match.replace(/width="[^"]*"/gi, '').replace(/width='[^']*'/gi, '');
		match = match.replace(/height="[^"]*"/gi, '').replace(/height='[^']*'/gi, '');
		return match;
	});
	// 修改所有style里的width属性为max-width:100%
	newContent = newContent.replace(/style="[^"]*"/gi, function(match, capture) {
		console.log('match11', match)
		match = match.replace(/width:[^;]*;/gi, 'max-width:100%;').replace(/width:[^;]*;/gi,
			'max-width:100%;');
		return match;
	});
	// 去掉<br/>标签
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	// img标签添加style属性：max-width:100%;height:auto
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	// 返回 处理后地结果
	return newContent;
}

// 获取商城设置
export const getSetting = (init = false) => {
	if ((!storage.getItem('base_setting') && !!storage.getItem('token')) || (!!storage.getItem('token') && init)) {
		return new Promise((resolve, reject) => {
			// Promise.all([api.get('/user/api/customerSet/addressAndPhone', {}, {
			// 	noToast: true
			// }),api.get('/user/api/dealer/info', {}, {
			// 	noToast: true
			// })]).then(([res1,res2]) => {
			// 	storage.setItem('base_setting', {
			// 		...res1.data?res1.data:{},
			// 		...res2.data?res2.data:{}
			// 	})
			// 	resolve({
			// 		...res1.data?res1.data:{},
			// 		...res2.data?res2.data:{}
			// 	})
			// }).catch(err => {
			// 	reject(err)
			// })
			api.get('/user/api/customerSet/addressAndPhone', {}, {
				noToast: true
			}).then((res) => {
				storage.setItem('base_setting', {
					...res.data ? res.data : {},
				})
				resolve({
					...res.data ? res.data : {},
				})
			}).catch(err => {
				reject(err)
			})
		})
	}
}

// 数字转大写
export function numberToChinese(num) {
	var chinese = "";
	var unit = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
	var digit = ["", "十", "百", "千", "万", "亿"];

	var numStr = num.toString();
	var len = numStr.length;
	for (var i = 0; i < len; i++) {
		var currentNum = parseInt(numStr[i]);
		chinese += unit[currentNum] + digit[len - i - 1];
	}
	return chinese;
}

export function getUserReq() {
	const userType = store.state.userType;
	switch (userType) {
		case 4:
			return '/user/api/user/info';
		case 3:
			if (store.state.appType == BASE.USER_TYPE) {
				return '/user/api/user/info';
			}
			return '/user/api/dealer/info';
		default:
			return '/user/api/auth/userInfo';
	}
}

export function getFullTime(time) {
	return new Date(moment().format('yyyy-MM-DD') + ' ' + time).getTime()
}

export function getCountdownformat(time) {
	return time && (time - 1000 * 60 * 60 * 24 > 0) ? 'DD天HH:mm:ss' : 'HH:mm:ss'
}

export function handlePreview(current, urls) {
	uni.previewImage({
		current,
		urls
	})
}

export const redirectToLogin = (showToastFlag = true) => {
	uni.removeStorageSync('token')
	uni.removeStorageSync('refreshToken')
	uni.removeStorageSync('tokenType')
	store.commit('setToken', '')
	if (showToastFlag)
		showToast('请登录')
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let currentPage = '/' + routes[routes.length - 1].route;

	const options = routes[routes.length - 1].options
	console.log(options,1111111)

	let urlargs = `${currentPage}?`

	for (let key in options) {

		const value = options[key]

		urlargs += `${key}=${value}&`

	}

	urlargs = urlargs.substring(0, urlargs.length - 1)
	setTimeout(() => {
		uni.reLaunch({
			url: `/pages/account/pages/login${currentPage=='pages/account/pages/login'?'':('?backUrl='+encodeURIComponent(urlargs))}`
		})
	}, showToastFlag ? 1500 : 0)
}

/* 权限控制 */
export const permis = (needRefresh = true) => {
	return new Promise((resolve, reject) => {
		if (!!storage.getItem('token')) {
			resolve()
		} else if (needRefresh) {
			redirectToLogin()
			reject()
		} else {
			showModal({
				title: '提示',
				confirmText: '去登录',
				content: '您还未登录'
			}).then(() => {
				redirectToLogin(false)
				reject()
			}).catch(() => {
				reject()
			})
		}
	})
}

export const modalRedirectToLogin = () => {
	showModal({
		title: '提示',
		confirmText: '去登录',
		content: '您还未登录'
	}).then(() => {
		redirectToLogin(false)
	})
}

export const goodsTypeDir = (type) => {
	if (!type) {
		return 1
	}
	const type1 = Number(type)
	const dir = {
		null: 1,
		0: 1,
		1: 4,
		2: 3,
		3: 5,
		4: 2,
		5: 6,
	}
	return dir[type1]
}

export const goodsTypeReDir = (type) => {
	if (!type) {
		return 0
	}
	const type1 = Number(type)
	const dir = {
		1: 0,
		2: 4,
		3: 2,
		4: 1,
		5: 3,
		6: 5
	}
	return dir[type1]
}

export const orderSysStatus2status = (status) => {
	const statusDir = {
		1: 1,
		2: 2,
		3: 3,
		4: 4,
		5: 5,
		6: 6,
		7: 7,
		8: 7,
		9: 7,
		10: 7,
		11: 7,
		12: 7,
		13: 8,
		14: 9,
		15: 10,
		16: 11,
		17: 12,
		18: 13
	}
	return statusDir[status]
}

export default {
	hideTel,
	loading,
	showToast,
	navigateBack,
	permis,
	hideName,
	getStaticUrl,
	getUserType,
	getOrderStatus,
	isEmpty,
	floatMul,
	floatAdd,
	showModal,
	getFunctionRange,
	formatRichText,
	getSetting,
	numberToChinese,
	getUserReq,
	getFullTime,
	floatSub,
	getCountdownformat,
	handlePreview,
	redirectToLogin,
	goodsTypeDir,
	goodsTypeReDir,
	orderSysStatus2status,
	modalRedirectToLogin
}